//
//  WXSLoginViewController.m
//  SleepBooks
//
//  Created by rimi on 16/9/19.
//  Copyright © 2016年 rimi. All rights reserved.
//

#import "WXSLoginViewController.h"


@interface WXSLoginViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *userName;
@property (strong, nonatomic) UITextField *password;
@property (strong, nonatomic) UIButton *loginBtn;

@end

@implementation WXSLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

// set subviews
- (void)setupSubviews{
    self.title = @"登录";
    [self setupBackBarButton];
    
    UIImageView *bgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg"]];
    [bgView setFrame:CGRectMake(0, 0, kBaseWidth, kBaesHeight)];
    [self.view addSubview:bgView];
    
    self.userName.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.password.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.navigationController.navigationBar.translucent = YES;
    
    self.userName.keyboardType = UIKeyboardTypeDefault;
    self.userName.returnKeyType = UIReturnKeyNext;
    [self.userName becomeFirstResponder];
    
    self.password.keyboardType = UIKeyboardTypeDefault;
    self.password.returnKeyType = UIReturnKeyDone;
    
    self.password.delegate = self;
    self.userName.delegate = self;

    UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(20, 120, 60, 40)];
    UILabel *password = [[UILabel alloc]initWithFrame:CGRectMake(20, 180, 60, 40)];
    
    userName.text = @"账号";
    password.text = @"密码";
    
    userName.textColor = [UIColor whiteColor];
    password.textColor = [UIColor whiteColor];
    
    userName.font = [UIFont systemFontOfSize:16];
    password.font = [UIFont systemFontOfSize:16];
    
    [self.view addSubview:userName];
    [self.view addSubview:password];
    
    [self.view addSubview:self.userName];
    [self.view addSubview:self.password];
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.frame = CGRectMake(20, 300, kBaseWidth-40, 40);
    _loginBtn.backgroundColor = [UIColor lightGrayColor];
    _loginBtn.layer.cornerRadius = 5;
    _loginBtn.layer.masksToBounds = YES;
    [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_loginBtn];
}

#pragma mark - button action

- (void)login{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInfo"];
    [query whereKey:@"username" equalTo:self.userName.text];
    [query whereKey:@"password" equalTo:self.password.text];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSArray<AVObject *> *userInfo = objects;
        if (userInfo.firstObject == nil) {
            AlertViewController *alert = [[AlertViewController alloc]initWithTitle:@"账号或者密码错误"];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            NSLog(@"登录成功");
            [WXSUserModel shareUserValue].isLogin = YES;
            if (self.returnNameBlock != nil) {
                self.returnNameBlock(self.userName.text);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
            NSLog(@"%@",userInfo);
    }];
}

#pragma mark - private method

- (void)returnName:(ReturnNameBlock)block{
    self.returnNameBlock = block;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.userName) {
        //注销响应者
        [self.userName resignFirstResponder];
        [self.password becomeFirstResponder];
    }
    
    if (textField == self.password) {
        [self.password resignFirstResponder];
        [self login];
    }
    
    return YES;
}

//限制输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSUInteger length = textField.text.length - range.length + string.length;

    if (textField == self.userName) {
        if (string.length) {
            NSString *regex = @"[a-zA-Z0-9\u4e00-\u9fa5]+";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            
            return [pred evaluateWithObject: string];
        }
        return true;
    }else if (textField == self.password){
        if (length > 5) {
            _loginBtn.enabled = YES;
            _loginBtn.backgroundColor = [UIColor colorWithRed:0.049 green:1.000 blue:0.934 alpha:1.000];
        }else{
            _loginBtn.enabled = NO;
            _loginBtn.backgroundColor = [UIColor lightGrayColor];
        }
        
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALLSTRING] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        
        return [string isEqualToString:filtered];
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}

#pragma mark - lazy load

- (UITextField *)userName{
    if (!_userName) {
        _userName = [[UITextField alloc]initWithFrame:CGRectMake(60, 120, kBaseWidth-80, 30)];
        _userName.backgroundColor = [UIColor whiteColor];
        _userName.placeholder = @"请输入账号";
        _userName.font = [UIFont systemFontOfSize:15];
        _userName.layer.cornerRadius = 5;
        _userName.layer.masksToBounds = YES;
    }
    return _userName;
}

- (UITextField *)password{
    if (!_password) {
        _password = [[UITextField alloc]initWithFrame:CGRectMake(60, 178, kBaseWidth-80, 30)];
        _password.backgroundColor = [UIColor whiteColor];
        _password.placeholder = @"请输入密码";
        _password.font = [UIFont systemFontOfSize:15];
        _password.layer.cornerRadius = 5;
        _password.layer.masksToBounds = YES;
        _password.secureTextEntry = YES;

    }
    return _password;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
